import pymongo
import requests

class Judger:

    def __init__(self,client):
        self.client = client    #连接数据库

    def judge_proxies(self):
        ##循环测试所有集合中的代理，可用的存入proxyCanUse
        with self.client as client:
            db = client.ipPool
            collectionsList = db.list_collection_names()
            for onecollection in collectionsList:
                if onecollection != 'proxyCanUse':
                    self._loop_infos(db,onecollection)

    def _loop_infos(self,db,onecollection):
        ##循环一个集合中的数据，可用的存入proxyCanUse
        proxyInfos = db[onecollection].find({},{'_id':0})
        for proxyInfo in proxyInfos:
            print(onecollection)
            if self._is_proxy_can_use(proxyInfo):
                db.proxyCanUse.insert_one(proxyInfo)


    def _is_proxy_can_use(self,proxyInfo):
        ##测试代理可用性,可用返回True，不可返回False
        url = 'http://icanhazip.com/'   #测试网站
        ip = proxyInfo['ip']
        port = proxyInfo['port']
        protocol = proxyInfo['protocol']
        proxy = {
            'http':protocol + '://' + ip +':' + port,
            'https':protocol + '://' + ip +':' + port
            }    #组装代理
        
        requests.adapters.DEFAULT_RETRIES = 3   #设置重连次数
        try:
            resp = requests.get(url,proxies=proxy,timeout=10)
            getIP = resp.text.strip()
            if getIP == ip:
                print("代理：" + ip + " 有效")
                return True
            else:
                print(ip + "返回ip数值不一"+ getIP + "无效")
                return False
        except:
            print(ip + "代理无法连接，无效")
            return False
